package com.cfs.daoimpl.sys;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.cfs.po.sys.Right;
import com.cfs.po.sys.Role;


/**
 * 角色管理dao
 * 
 * @author wang.yujie
 * @since 2012-12-23
 * @version 1.0
 */
public class RoleDao extends Dao {

DictDao dictDao;

//	public void setDictDao(DictDao dictDao) {
//		this.dictDao = dictDao;
//	}

	// private static Map<Long, Role> allRole = new HashMap<Long, Role>();
	private RowMapper<Role> mapper = new RowMapper<Role>() {
		@Override
		public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
			Role role = new Role();
			role.setId(rs.getLong("id"));
			role.setName(rs.getString("name"));
			role.setDescription(rs.getString("description"));
			return role;
		}
	};

	public Role get(Long roleId) {
		Role role = null;
		List<Role> list = jdbcTemplate.query(DB_SQL.ROLE_QUERY_BY_ID, new Object[] { roleId }, new RowMapper<Role>() {

			@Override
			public Role mapRow(ResultSet rs, int arg1) throws SQLException {
				// TODO Auto-generated method stub
				Role role = new Role();
				role.setId(rs.getLong("id"));
				role.setName(rs.getString("name"));
				role.setDescription(rs.getString("description"));
				return role;
			}

		});
		role = list.get(0);
		role.setRights(jdbcTemplate.query(DB_SQL.ROLE_RIGHT_QUERY_URI_BY_ROLE, new Object[] { role.getId() }, new RowMapper<String>() {
			@Override
			public String mapRow(ResultSet rs, int arg1) throws SQLException {
				return rs.getString(1);
			}
		}));
		// return allRole.get(roleId);
		return role;
	}

	/**
	 * 加载角色缓存
	 */
	public void initAll() {
		Map<Long, Role> roleTemp = new HashMap<Long, Role>();
		List<Role> list = jdbcTemplate.query(DB_SQL.ROLE_QUERY_ALL, mapper);

		for (Role r : list) {
			r.setRights(jdbcTemplate.query(DB_SQL.ROLE_RIGHT_QUERY_URI_BY_ROLE, new Object[] { r.getId() }, new RowMapper<String>() {
				@Override
				public String mapRow(ResultSet rs, int arg1) throws SQLException {
					return rs.getString(1);
				}
			}));

			roleTemp.put(r.getId(), r);

			// System.out.println(r.getId() + " - " + r.getName() + " - " +
			// r.getRights());
		}
		// allRole.clear();
		// allRole = roleTemp;
		System.out.println("Init Role: ......OK");
	}

	@Override
	public void setJdbcTemplate(JdbcTemplate t) {
		super.setJdbcTemplate(t);
		// initAll();
	}

	public boolean checkRights(long roleId, String uri) {

		List<String> list = queryRoleRight(roleId);
		return list.contains(uri);
		// return allRole.get(roleId).getRights().contains(uri);
	}

	//为了缓存 拦截方便，把RoleDao checkRights中查询权限方法拿到这里 
	public List<String> queryRoleRight(long roleId){
		return jdbcTemplate.query(DB_SQL.ROLE_RIGHT_QUERY_URI_BY_ROLE, new Object[]{roleId},new RowMapper<String>(){
			@Override
			public String mapRow(ResultSet rs, int arg1) throws SQLException {
				return rs.getString(1);
			}});
	}

	/**
	 * 角色批量添加
	 */
	public int add(Role[] roles) {
		String sql = DB_SQL.ROLE_INS;
		List<Object[]> paramList = new ArrayList<Object[]>();
		for (Role role : roles) {
			paramList.add(new Object[] { role.getName(), role.getDescription() });
		}
		int[] rows = jdbcTemplate.batchUpdate(sql, paramList);
		int p = 0;
		for (int x : rows) {
			if (x == 1)
				p++;
		}
		System.out.println("role 批量添加  执行:" + p);
		// initAll();

		return p;
	}

	/**
	 * 角色更新
	 */
	public int update(Role[] roles) {
		String sql = DB_SQL.ROLE_UPD_BY_ID;

		List<Object[]> pList = new ArrayList<Object[]>();
		for (Role r : roles) {
			pList.add(new Object[] { r.getName(), r.getDescription(), r.getId() });
		}

		int[] rows = jdbcTemplate.batchUpdate(sql, pList);
		int p = 0;
		for (int x : rows) {
			if (x == 1)
				p++;
		}

		System.out.println("role update 执行:" + p);
		// initAll();

		return p;
	}

	/**
	 * 角色删除
	 */
	public int delete(long[] ids) {
		String sql = DB_SQL.ROLE_DEL_BY_ID;
		List<Object[]> paramList = new ArrayList<Object[]>();
		for (long id : ids) {
			paramList.add(new Object[] { id });
		}
		int[] rows = jdbcTemplate.batchUpdate(sql, paramList);
		int p = 0;
		for (int x : rows) {
			if (x == 1)
				p++;
		}

		System.out.println("role 执行删除：" + p);
		// initAll();

		return p;
	}

	/**
	 * 获取角色列表查询人员
	 * 
	 * @param rid
	 * @return
	 */
	public List<Role> lists(int level) {
		List<Role> list = new ArrayList<Role>();
		String sql = "";
		sql="SELECT * FROM TB_ROLE WHERE LEVELS>=? AND ID>1 ";
//		if (level == 1) {
//			sql = "SELECT * FROM TB_ROLE WHERE LEVELS>=?";
//		} else {
//			sql = "SELECT * FROM TB_ROLE WHERE LEVELS>?";
//		}

		list = jdbcTemplate.query(sql, new Object[] { level }, mapper);

		return list;
	}

	/**
	 * 获取角色列表
	 * 
	 * @param rid
	 * @return
	 */
	public List<Role> list(int level) {
		List<Role> list = new ArrayList<Role>();
		String sql = "";
		sql="SELECT * FROM TB_ROLE WHERE LEVELS=? and id>1 ";
//		if (level == 1) {
//			sql = "SELECT * FROM TB_ROLE WHERE LEVELS>=?";
//		} else {
//			sql = "SELECT * FROM TB_ROLE WHERE LEVELS>?";
//		}

		list = jdbcTemplate.query(sql, new Object[] { level }, mapper);

		return list;
	}

	/**
	 * 根据rid获取角色
	 * 
	 * @param rid
	 * @return
	 */
	public Role query(long rid) {
		List<Role> list = jdbcTemplate.query(DB_SQL.ROLE_QUERY_BY_ID, new Object[] { rid }, mapper);
		return list == null || list.size() != 1 ? null : list.get(0);
	}

	/**
	 * 根据rid获取权限列表
	 * 
	 * @param rid
	 * @return
	 */
	public List<Right> queryRights(Long rid) {
		List<Right> list = jdbcTemplate.query(DB_SQL.RIGHT_QUERY_BY_ROLE, new Object[] { rid }, new RowMapper<Right>() {
			@Override
			public Right mapRow(ResultSet rs, int arg1) throws SQLException {
				Right r = new Right();
				r.setId(rs.getLong("ID"));
				r.setName(rs.getString("NAME"));
				r.setUri(rs.getString("URI"));

				return r;
			}
		});
		return list;
	}

	/**
	 * 获取全部权限列表
	 * 
	 * @param rid
	 * @return
	 */
	public List<Right> queryAllRights() {
		List<Right> list = jdbcTemplate.query(DB_SQL.RIGHT_QUERY_ALL, new RowMapper<Right>() {
			@Override
			public Right mapRow(ResultSet rs, int arg1) throws SQLException {
				Right r = new Right();
				r.setId(rs.getLong("ID"));
				r.setName(rs.getString("NAME"));
				r.setUri(rs.getString("URI"));

				return r;
			}
		});
		return list;
	}

	/**
	 * 角色权限维护
	 * 
	 * @param roleId
	 * @param rights
	 * @return
	 */
	public int updateRight(Long roleId, List<Right> rights) {
		// List<Object[]> upList = new ArrayList<Object[]>();
		List<Object[]> addList = new ArrayList<Object[]>();

		List<Object[]> ids = jdbcTemplate.query(DB_SQL.ROLE_RIGHT_QUERY_BY_ROLE, new Object[] { roleId }, new RowMapper<Object[]>() {
			@Override
			public Object[] mapRow(ResultSet rs, int arg1) throws SQLException {
				return new Object[] { rs.getLong(1), rs.getLong(2) };
			}
		});

		System.out.println("IDS: " + ids.size());
		for (Right r : rights) {
			// if(ids.size()>0){
			// Object[] id = ids.remove(0);
			// upList.add(new Object[]{r.getId(), id[0], id[1]});
			// }else{
			addList.add(new Object[] { roleId, r.getId() });
			// }
		}

		int[] a, b, c;
		a = b = c = new int[0];
		if (ids.size() > 0) {
			c = jdbcTemplate.batchUpdate(DB_SQL.ROLE_RIGHT_DEL, ids);
			System.out.println("DEL: " + c.length);
		}
		// if(upList.size()>0){
		// a = jdbcTemplate.batchUpdate(DB_SQL.ROLE_RIGHT_UPD_RIGHT, upList);
		// }
		if (addList.size() > 0) {
			b = jdbcTemplate.batchUpdate(DB_SQL.ROLE_RIGHT_ADD, addList);
			System.out.println("ADD: " + b.length);
		}

		// initAll();

		return a.length + b.length + c.length;
	}
}
